package carassius.GUI;

import carassius.DAL.AquariumRow;
import carassius.DAL.Database;
import java.awt.Container;
import java.awt.Frame;
import java.sql.SQLException;
import java.util.ResourceBundle;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;

/**
 *
 * @author siebz0r
 */
public class AquariumList
		extends ListWithMenu
{
	private Frame parentFrame;

	private Frame getParentFrame()
	{
		if (parentFrame == null)
		{
			Container parent = getParent();
			while (parent != null)
			{
				if (parent instanceof Frame)
				{
					break;
				}
				parent = parent.getParent();
			}
			if (parent instanceof Frame)
			{
				parentFrame = (Frame) parent;
			}
		}
		return parentFrame;
	}

	@Override
	void add()
	{
		new AquariumForm(getParentFrame()).setVisible(true);
	}

	@Override
	void remove()
	{
		if (getSelectedValue() != null)
		{
			AquariumRow row = (AquariumRow) getSelectedValue();
			StringBuilder sb = new StringBuilder();
			sb.append(ResourceBundle.getBundle("carassius.resources.Messages").getString("DeleteAquariumQuestion"));
			sb.append("\n");
			sb.append(row.getName());
			if (JOptionPane.showConfirmDialog(this,
					sb.toString(),
					ResourceBundle.getBundle("carassius.resources.Messages").getString("DeleteAquariumQuestionTitle"),
					JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION)
			{
				try
				{
					Database.getAquariumTable().delete(row);
					DefaultListModel model = (DefaultListModel) getModel();
					model.removeElement(row);
				}
				catch (SQLException ex)
				{
					JOptionPane.showMessageDialog(this,
							ResourceBundle.getBundle("carassius.resources.Messages").getString("DeleteAquariumError"),
							ResourceBundle.getBundle("carassius.resources.Messages").getString("DeleteAquariumErrorTitle"),
							JOptionPane.ERROR_MESSAGE);
				}
			}
		}
	}

	@Override
	void edit()
	{
		if (getSelectedValue() instanceof AquariumRow)
		{
			new AquariumForm(getParentFrame(), (AquariumRow) getSelectedValue()).setVisible(true);
		}
	}
}
